// miniprogram/pages/detail/detail.js
const app = getApp();
const hexoparse = require('../../utils/hexoparse.js');
const util = require('../../utils/util.js')
const AV = require('../../libs/leancloud/av-weapp-min.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isGank: false,
        shareBGURL: 'https://ae01.alicdn.com/kf/H9e5d88dcf1944a0eb8258e0c0eb8d20e7.jpg',
        // towxml 链接处理
        linkIsFirstTap: true,
        previewImgs: [],
        // 广告位控制
        adBannerLoadStatus: [
            false, false
        ],
        adShow: false,
        ad3Show: false,
        ad3ID: "",
        ad2Show: false,
        ad2ID: "",
        ad2Timeout: 30, // unit: s
        ad4ID: "",
        ad4Show: false,
        ad5ID: "",
        ad5Show: false,
        setInter: null,
        currentTimeCount: 0,
        interstitialAd2: null,
        interstitialAd2IsClose: false,

        showComment: true,
        commentSensitiveWords: [],
        showFloatMenu: true,
        hiddenModalPassword: true,

        official_account: true,
        official_account_url: "https://www.xiaobaiai.net/imgs/20200428174933.gif",

        menuMainItem: {
            "icon": "../../images/menu_main.png"
        },
        menuSubItems: [{
                "id": "1",
                "icon": "../../images/menu_collection.png",
                "method": "addCollection",
            },
            {
                "id": "2",
                "icon": "../../images/menu_theme.png",
                "method": "checkoutTheme",
            },
            {
                "id": "3",
                "icon": "../../images/menu_backtop.png",
                "method": "backToTop",
            },
        ],

        title: '标题',
        key: '20190814195020',
        cover: '',
        description: '',
        baseURL: '',
        password: '',
        passwordDesc: '',
        inputPassword: '',
        header: {},
        isDark: false,
        articleInfo: {
            'author': 'Ethan',
            'page_views': 520,
            'comment_count': 17,
            'thumbs_up_count': 10,
            'date': '2019-09-26 12:30:00'
        },
        articleURL: '',
        articleID: '',
        articleData: {},
        // 导航栏动态设置标题
        isOverTile: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let that = this;
        // 检查NewWxComment显示设置
        console.log('onLoad')
        if (app.globalData.config) {
            that.data.adShow = app.globalData.config.ad.show;
            that.data.ad2Show = app.globalData.config.ad.ad2.show;
            that.data.ad2ID = app.globalData.config.ad.ad2.id;
            that.data.ad2Timeout = app.globalData.config.ad.ad2.timeout;
            that.data.ad3Show = app.globalData.config.ad.ad3.show;
            that.data.ad3ID = app.globalData.config.ad.ad3.id;
            that.data.ad4Show = app.globalData.config.ad.ad4.show;
            that.data.ad4ID = app.globalData.config.ad.ad4.id;
            that.data.ad5Show = app.globalData.config.ad.ad5.show;
            that.data.ad5ID = app.globalData.config.ad.ad5.id;

            // 最小出现广告时间为20s
            if (that.data.ad2Timeout < 20) {
                that.data.ad2Timeout = 20;
            }

            that.setData({
                adShow: that.data.adShow,
                ad3Show: that.data.ad3Show,
                ad3ID: that.data.ad3ID,
                ad4ID: that.data.ad4ID,
                ad4Show: that.data.ad4Show,
                ad5ID: that.data.ad5ID,
                ad5Show: that.data.ad5Show
            })

            if (that.data.adShow && that.data.ad2Show) {
                // 插屏广告初始化
                if (wx.createInterstitialAd) {
                    that.data.interstitialAd2 = wx.createInterstitialAd({
                        adUnitId: that.data.ad2ID
                    })
                    that.data.interstitialAd2.onLoad(() => {
                        // 加载成功，启动计时器
                        console.log('插屏式广告初始化成功，启动计时器')
                        that.startTimer();
                    })
                    that.data.interstitialAd2.onError((err) => {
                        console.log('创建插屏广告失败')
                    })
                    that.data.interstitialAd2.onClose(() => {
                        that.interstitialAd2IsClose = true;
                    })
                }

            }

            if (!app.globalData.config.global.comment) {
                that.setData({
                    showComment: false,
                    official_account_url: app.globalData.config.global.official_account_url
                })
            }
            if (app.globalData.config.global.official_account == false) {
                that.setData({
                    official_account: false
                })
            }
            if (app.globalData.config.global.comment_filter) {
                that.setData({
                    commentSensitiveWords: app.globalData.config.global.comment_filter
                })
            }
        }

        // 设备导航栏无标题
        wx.setNavigationBarTitle({
            title: ''
        })
        // 主题设置
        that.checkTheme();
        // 文章信息设置，获取数据
        if (that.getArticleBaseInfo(options)) {
            that.setArticleInfo(options);
            if (!that.data.password) {
                if (that.data.key && that.data.key.length > 0) {
                    that.fetechArticleData();
                }
            } else {
                // nothing to do
            }
        } else {
            // 参数错误
            // TODO
        }
    },
    // towxml 绑定tap事件处理
    __bind_tap: function(event) {
        //console.log(event);
        let that = this;
        // 隐藏评论组件菜单栏
        if (this.data.showComment) {
            let newWxComment = this.selectComponent('#NewWxComment');
            newWxComment.hiddenMenubox();
        }

        if (that.data.linkIsFirstTap) {
            that.data.linkIsFirstTap = false;
            // Bug: 会触发两次tap
            // 处理图片预览功能
            if (event.target.dataset._el.tag == "image") {
                wx.previewImage({
                    current: event.target.dataset._el.attr.src, //当前图片地址
                    urls: that.data.previewImgs,  //所有要预览的图片的地址集合 数组形式
                    success: function (res) {

                    },
                    fail: function (res) {

                    },
                    complete: function (res) {

                    },
                })
                return;
            } 
            // else if (event.target.dataset._el.tag == 'image' && that.data.isGank) {
            //     console.log('跳转干货Swpier显示')
            //     wx.navigateTo({
            //         url: '../launch/launch?is_gank=true&gank_list=' + that.data.previewImgs,
            //     })
            //     return;
            // }

            // 处理内部链接
            let link = event.target.dataset._el.attr.href;
            if (!link) {
                // space click handle
                return;
            }
            let link_item_list = link.split('.');
            let link_type = link_item_list[link_item_list.length - 1];
            //console.log(link_type);
            if (link_type == 'htm' || link_type == 'html') {
                wx.showModal({
                    title: '提示',
                    content: '个人小程序不支持打开外部链接！',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            // 复制到黏贴板
                            wx.setClipboardData({
                                data: link,
                                success(res) {

                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                })
            } else if (link_type == 'md') {
                console.log('内部md链接');
                // TODO
            } else {
                wx.showModal({
                    title: '提示',
                    content: '个人小程序不支持打开外部链接！',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            // 其他非htm/html/md后缀链接
                            // 复制到黏贴板
                            wx.setClipboardData({
                                data: link,
                                success(res) {

                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                })
            }
        }
        that.data.linkIsFirstTap = false;
        setTimeout(function () {
            that.data.linkIsFirstTap = true;
        }, 1000);
    },
    startTimer: function() {
        let that = this;
        // 将计时器赋值给setInter
        that.data.setInter = setInterval(
            function() {
                that.data.currentTimeCount = that.data.currentTimeCount + 1;
                // console.log('setInterval==' + that.data.currentTimeCount);
                if (that.data.currentTimeCount > that.data.ad2Timeout) {
                    // 清零
                    that.data.currentTimeCount = 0;
                    // 显示广告
                    that.showInterstitialAD();
                }
            }, 1000);
    },
    stopTimer: function() {
        let that = this;
        // 清除计时器
        if (that.data.setInter) {
            console.log('清除定时器')
            clearInterval(that.data.setInter);
        }
    },
    showInterstitialAD: function() {
        let that = this;
        if (that.data.interstitialAd2) {
            that.data.interstitialAd2.show().catch((err) => {
                console.error(err)
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        console.log('onShow')
        let that = this;
        let browse_record = wx.getStorageSync('browse_record') || [];

        // "key": "201909291348",
        // "title": "浏览历史",
        // "password": "",
        // "cover": "",
        // "description": ""
        let item = {
            "key": that.data.key,
            "title": that.data.title,
            "author": that.data.articleInfo.author,
            "password": that.data.password ? that.data.password : '',
            "cover": that.data.cover ? that.data.cover : '',
            "description": that.data.description ? that.data.description.substring(0, 60) + '...' : ""
        }

        // 浏览记录总保证最后浏览为最新
        // TODO: 限制最大记录数
        if (browse_record.length == 0 || app.deleteArraySpecifyKey(browse_record, that.data.key, true)) {
            browse_record.unshift(item);
            //console.log(item);
            wx.setStorage({
                key: "browse_record",
                data: browse_record
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        console.log('onHide')
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        console.log('onUnload')
        this.stopTimer();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        console.log('onReachBottom');
        if (this.data.showComment) {
            let newWxComment = this.selectComponent('#NewWxComment');
            newWxComment.onReachBottom();
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        let that = this;

        return {
            title: that.data.title,
            path: '/pages/detail/detail?title=' + that.data.title + '&key=' + that.data.key + '&author=' + that.data.articleInfo.author +
                '&comment_count=' + that.data.articleInfo.comment_count + '&page_views=' + that.data.articleInfo.page_views +
                '&thumbs_up_count=' + that.data.articleInfo.thumbs_up_count + '&date=' + that.data.articleInfo.date + '&password=' + that.data.articleInfo.password + '&password_desc=' + that.data.articleInfo.password_desc + '&is_gank=' + that.data.isGank,
            imageUrl: that.data.shareBGURL
        }
    },
    writeCommentSuccess: function() {
        console.log('触发评论成功事件')
        let that = this;
        let comment_record = wx.getStorageSync('comment_record') || [];

        let item = {
            "key": that.data.key,
            "title": that.data.title,
            "author": that.data.articleInfo.author,
            "password": that.data.password ? that.data.password : '',
            "cover": that.data.cover ? that.data.cover : '',
            "description": that.data.description ? that.data.description.substring(0, 60) + '...' : ""
        }

        // 浏览记录总保证最后浏览为最新
        // TODO: 限制最大记录数
        if (comment_record.length == 0 || app.deleteArraySpecifyKey(comment_record, that.data.key, true)) {
            comment_record.unshift(item);
            //console.log(item);
            wx.setStorage({
                key: "comment_record",
                data: comment_record
            })
        }
    },
    writeLikeSuccess: function(e) {
        console.log('触发点赞成功事件')
        let that = this;
        let like_record = wx.getStorageSync('like_record') || [];

        let item = {
            "key": that.data.key,
            "title": that.data.title,
            "author": that.data.articleInfo.author,
            "password": that.data.password ? that.data.password : '',
            "cover": that.data.cover ? that.data.cover : '',
            "description": that.data.description ? that.data.description.substring(0, 60) + '...' : ""
        }

        // 浏览记录总保证最后浏览为最新
        // TODO: 限制最大记录数
        if (like_record.length == 0 || app.deleteArraySpecifyKey(like_record, that.data.key, true)) {
            like_record.unshift(item);
            //console.log(item);
            wx.setStorage({
                key: "like_record",
                data: like_record
            })
        }
    },
    getArticleBaseInfo: function(options) {
        let that = this;
        if (options.is_gank == true || options.is_gank == 'true') {
            that.data.isGank = true
        } else {
            that.data.isGank = false;
        }
        
        that.data.key = options.key;
        that.data.title = options.title;
        that.data.password = options.password ? options.password : '';
        that.data.passwordDesc = options.password_desc ? options.password_desc : '';
        that.data.cover = options.cover ? options.cover : '';
        that.data.description = options.desc ? options.desc : '';
        that.data.articleInfo.author = options.author ? options.author : '';
        // 分享背景图片
        if (that.data.cover) {
            that.data.shareBGURL = that.data.cover;
        }
        that.setData({
            isGank: that.data.isGank,
            key: that.data.key,
            title: that.data.title,
            password: that.data.password,
            passwordDesc: that.data.passwordDesc,
            hiddenModalPassword: that.data.password ? false : true,
            cover: that.data.cover,
            description: that.data.description        
        })
        console.log('is_gank : ' + options.is_gank)

        // 设置格式参加hexo _config.yml文件
        // permalink: :year/:title.html
        // /2019/20190727172958.html
        console.log(that.data.key)
        if (that.data.key && that.data.key.indexOf('.html') == -1) {
            that.data.aritcleURL = '/' + that.data.key.substring(0, 4) + '/' + that.data.key + '.html';
            that.data.articleID = '/' + that.data.key.substring(0, 4) + '/' + that.data.key + '.html';
            that.data.articleURL = that.data.articleID;
            return true;
        } else {
            console.error('article key is emtpy');
            return false;
        }
    },
    setArticleInfo: function(options) {
        let that = this;
        let pages = getCurrentPages();

        // >=1 : 暂且不获取最新统计信息
        // > 1: 仅处理其他页面跳转情况
        if (pages.length >= 1) {
            // 从其他页面跳转而来
            that.data.articleInfo['author'] = options.author;
            that.data.articleInfo['page_views'] = options.page_views;
            that.data.articleInfo['comment_count'] = options.comment_count;
            that.data.articleInfo['thumbs_up_count'] = options.thumbs_up_count;
            that.data.articleInfo['date'] = options.date;
            that.data.articleInfo['password'] = options.password;
            that.data.articleInfo['password_desc'] = options.password_desc;
            if (options.page_views) {
                that.setData({
                    articleInfo: that.data.articleInfo,
                    title: that.data.title,
                    articleURL: that.data.articleURL,
                    articleID: that.data.articleID
                })
            } else {
                let key = '/' + that.data.key.substr(0, 4) + '/' + that.data.key + '.html';
                that.fetchArticleStatisticsData([key], function(status, result) {
                    if (status) {
                        //console.log(result)

                        that.data.articleInfo["page_views"] = result[0].attributes.time == undefined ? 0 : result[0].attributes.time;
                        that.data.articleInfo["comment_count"] = result[0].attributes.comments == undefined ? 0 : result[0].attributes.comments;
                        that.data.articleInfo["thumbs_up_count"] = result[0].attributes.likeUserList == undefined ? 0 : result[0].attributes.likeUserList.length;
                        that.data.articleInfo["date"] = result[0].createdAt == undefined ? 0 : util.getLocalDateTimeStr(result[0].createdAt);

                        that.setData({
                            articleInfo: that.data.articleInfo,
                            title: that.data.title,
                            articleURL: that.data.articleURL,
                            articleID: that.data.articleID
                        })
                    } else {

                    }
                })
            }
        } else {
            // 直接打开页面
            // 从数据库中获取数据,能够拿取最新的统计信息
            // TODO

        }
    },
    fetchArticleStatisticsData: function(keys, call_back) {
        //console.log(keys)
        let query = new AV.Query('Counter');
        query.containedIn('url', keys);
        query.find().then(ret => {
            //console.log(ret)
            call_back(true, ret);
        }).catch(ex => {
            console.log(ex.message);
            console.log(ex.code);
            if (ex.code == 101) {
                console.log('页面统计表未存在');
            }
            call_back(false, null);
        });
    },
    checkTheme: function() {
        let that = this;
        // 从本地缓存中获取当前主题设置
        // TODO

        // 背景色调节
        if (that.data.isDark) {
            that.setData({
                isDark: that.data.isDark
            })
            wx.setNavigationBarColor({
                frontColor: '#ffffff',
                backgroundColor: '#000000'
            })
            wx.setBackgroundColor({
                backgroundColor: '#000000'
            })
        } else {
            wx.setNavigationBarColor({
                frontColor: '#000000',
                backgroundColor: '#ffffff'
            })
        }
    },
    fetechArticleData: function() {
        let that = this;
        wx.showLoading({
            title: '加载中...',
        })
        setTimeout(function() {
            wx.hideLoading()
        }, 12000)
        let base_url = app.globalData.gitee.posts_url;
        if (that.data.isGank) {
            base_url = app.globalData.gitee.gank_url;
        }
        wx.request({
            url: base_url + '/' + that.data.key + '.md',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function(res) {
                console.log('请求文章数据成功');
                debugger
                let output = app.base64.decode(res.data.content);               
                that.parseArticleData(output, function(){
                    console.log('解析成功')
                    wx.hideLoading();
                });                
            },
            fail: function(e) {
                console.log('请求文章数据失败');
                wx.hideLoading();
            }
        })
    },
    parseArticleData: function(data, call_back) {
        let that = this;        
        let split_limit = 2;
        let md_content_list = data.split('---', split_limit);
        let md_header = md_content_list[1];
        that.data.header = hexoparse.getHeaderObj(md_header);       
        let offset = 3;
        let article_tmp = data.substr(data.indexOf('---', offset) + offset);        
        // 将markdown内容转换为towxml数据
        let md_data = app.towxml.toJson(article_tmp, 'markdown');        
        // 设置文档显示主题，默认'light'
        md_data.theme = that.data.isDark ? 'dark' : 'light';
        //console.log(md_data)        
        if (md_data && md_data.child && md_data.child.length > 20) {
            //console.log('md_data is too large')
            let md_data_child_len = md_data.child.length;            
            // 分四次设置数据
            that.data.articleData.id = md_data.id;
            that.data.articleData.node = md_data.node;
            that.data.articleData.theme = md_data.theme;
            that.data.articleData.child = [];
            const lazy_size = 40;
            const max_lazy_page = 50;
            //console.log(md_data_child_len)
            for (let i = 0; i < max_lazy_page; i++) {                
                if ((md_data_child_len - lazy_size * i) > lazy_size) {                
                    let slice = md_data.child.slice(i * lazy_size, i * lazy_size + lazy_size);                    
                    that.data.articleData.child = [].concat(that.data.articleData.child, slice)
                    that.setData({
                        articleData: that.data.articleData
                    })
                } else {                    
                    let slice = md_data.child.slice(i * lazy_size, i * lazy_size + (md_data_child_len - i * lazy_size));                    
                    that.data.articleData.child = [].concat(that.data.articleData.child, slice)
                    that.setData({
                        articleData: that.data.articleData
                    })
                    break;
                }
            }            
            call_back(true)
            
        } else {
            that.setData({
                articleData: md_data
            }, function () {                
                call_back(true)
            });        
        }
        // 获取当前文档所有图片链接
        if (md_data && md_data.child.length > 0) {
            for (let i = 0; i < md_data.child.length; i++) {
                if (md_data.child[i].node == 'element') {
                    if (md_data.child[i].child[0].tag == 'image') {
                        let url = md_data.child[i].child[0].attr.src;
                        that.data.previewImgs.push(url)
                    }
                }
            }
        }
    },
    onPageScroll(e) {
        let that = this;
        // console.log("page pos: " + e.scrollTop);
        // console.log(that.data.isOverTile);
        if (e.scrollTop >= 100 && !that.data.isOverTile) {
            that.data.isOverTile = true;
            wx.setNavigationBarTitle({
                title: that.data.title
            })
        } else if (e.scrollTop < 100 && that.data.isOverTile) {
            that.data.isOverTile = false;
            wx.setNavigationBarTitle({
                title: ''
            })
        } else {
            // nothing to do
        }
    },
    addCollection: function(e) {
        console.log('addCollection')
        let that = this;
        let collection_record = wx.getStorageSync('collection_record') || [];

        // "key": "201909291348",
        // "title": "浏览历史",
        // "password": "",
        // "cover": "",
        // "description": ""
        let item = {
            "key": that.data.key,
            "title": that.data.title,
            "author": that.data.articleInfo.author,
            "password": that.data.password,
            "cover": that.data.cover,
            "description": that.data.description.substr(0, 60) + '...'
        }

        // 浏览记录总保证最后浏览为最新
        // TODO: 限制最大记录数
        if (collection_record.length == 0 || app.deleteArraySpecifyKey(collection_record, that.data.key, true)) {
            collection_record.unshift(item);
            console.log(item);
            wx.setStorage({
                key: "collection_record",
                data: collection_record
            })

            wx.showToast({
                title: '收藏成功',
                icon: 'none',
                duration: 2000
            })
        }
    },
    checkoutTheme: function(e) {
        console.log(e)
    },
    backToTop: function(e) {
        console.log(e)
    },
    adLoadSuccess: function(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        that.data.adBannerLoadStatus[index] = true;
        that.setData({
            adBannerLoadStatus: that.data.adBannerLoadStatus
        })
    },
    adLoadError: function(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        that.data.adBannerLoadStatus[index] = false;
        that.setData({
            adBannerLoadStatus: that.data.adBannerLoadStatus
        })
    },
    modelPasswdConfirm: function(e) {
        let that = this;
        // console.log("modelPasswdConfirm")
        // console.log(this.data.password)
        // console.log(this.data.inputPassword)
        // console.log(this.data.password == this.data.inputPassword)
        if (this.data.inputPassword == this.data.password) {
            this.setData({
                hiddenModalPassword: true
            })
            if (that.data.key && that.data.key.length > 0) {
                that.fetechArticleData();                
            }           
            let newWxComment = this.selectComponent('#NewWxComment');
            newWxComment.updatePageCounter(); 
        } else {
            wx.showToast({
                title: '口令错误',
                icon: 'none',
                duration: 2000
            })
        }
    },
    modelPasswdCancel: function(e) {
        // console.log("modelPasswdCancel")
        // console.log(e)
        this.data.inputPassword = '';
        wx.navigateBack({
            delta: 1,
            hiddenModalPassword: true
        })
    },
    inputPassword: function(e) {
        // console.log("inputPassword")
        // console.log(e)
        this.data.inputPassword = e.detail.value;
    },
    // 公众号绑定加载
    officialAccountBindload: function(e) {
        console.log(e)
    },
    officialAccountBinderror: function(e) {
        console.log(e)
    },
    previewImage: function (e) {
        let current = e.target.dataset.src;
        console.log(current)
        console.log(e)
        let preview_urls = [];
        preview_urls.push(current);
        wx.previewImage({
            current: current,
            urls: preview_urls
        })
    }
})